package com.xhwl.data.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.dto.cent.sdata.AccountDetailDTO;
import com.xhwl.common.dto.cent.sdata.ProjectDTO;
import com.xhwl.common.enums.LogOperationTypeEnum;
import com.xhwl.common.enums.ModuleTypeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.utils.*;
import com.xhwl.common.utils.function.MyStringUtils;
import com.xhwl.common.vo.cent.sdata.ProjectByCityVO;
import com.xhwl.data.dao.ISceneDao;
import com.xhwl.data.pojo.vo.ProjectNameCheckedVO;
import com.xhwl.data.pojo.vo.ProjectVO;
import com.xhwl.data.service.*;
import com.xhwl.data.util.AutoCodeUtils;
import com.xhwl.data.util.CodePrefixConstant;
import com.xhwl.data.util.ValidatorUtil;
import com.xhwl.starter.log.LogTemplate;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 14:47 2021/3/2
 */
@RestController
public class ProjectController {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private ISceneDao sceneDao;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IProjectExtraService projectExtraService;

    @Autowired
    LogTemplate logTemplate;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    private static final String PROJECT_PAGE_FIELD = "PROJECT_PAGE_FIELD";

    private static final String KEY = "PROJECT:CODE";

    private static final Logger log = LoggerFactory.getLogger(ProjectController.class);

    /**
     * 前台项目分页查询
     *
     * @param projectQuery
     * @param account
     * @param page
     * @return
     */
    @RequestMapping(value = "/project/page")
    public ResultJson page(@RequestBody ProjectQuery projectQuery, Account account, Page page,Integer typeId) {
        if (null == projectQuery) {
            return ResultJson.fail("参数错误");
        }
        page.setOrders(OrderItem.descs("updated_at"));
        projectQuery.withAccountId(account.getId());
        Page<Project> projectPage = projectService.listPage(projectQuery, account, page);
        page.setRecords(convertView(projectPage.getRecords(),typeId));
        return ResultJson.success(page);
    }

    /**
     * 后台项目分页查询
     *
     * @param projectQuery
     * @return
     */
    @PostMapping("/project/admin/page")
    public ResultJson adminPage(@RequestBody ProjectQuery projectQuery) {
        if (null == projectQuery) {
            return ResultJson.fail("参数错误");
        }
        projectQuery.getPage().setOrders(OrderItem.descs("updated_at"));
        Page<Project> projectPage = projectService.listPage(projectQuery, null, projectQuery.getPage());
        Page<ProjectVO> projectVOPage = projectQuery.getPage();
        return ResultJson.success(projectVOPage.setRecords(convertView(projectPage.getRecords(),null)));
    }

    @RequestMapping(value = "/project/list", method = RequestMethod.POST)
    public ResultJson list(@RequestBody ProjectQuery projectQuery, Account account) {
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withAccountId(account.getId());
        List<Organization> list = organizationService.list(organizationQuery);
        if (list.isEmpty()) {
            log.warn("账号 {} {} 暂未关联组织信息", account.getId(), account.getName());
        }
        projectQuery.withEnterpriseIds(list.stream().map(l -> l.getEnterpriseId()).collect(Collectors.toList()));
        List<Project> projectList = projectService.list(projectQuery, account);
        return ResultJson.success(projectList);
    }

    @RequestMapping("/project/admin/list")
    public ResultJson listAdmin(@RequestBody ProjectQuery projectQuery){
        List<Project> projectList = projectService.list(projectQuery, null);
        if (projectQuery.getIsGroupByInitial()){
            List<ProjectVO> projectVOS = convertView(projectList,null);
            Map<String,List<ProjectVO>> listMap = new LinkedHashMap<>();
            listMap.put("#",null);
            for (int i=0;i<26;i++){
                String initial = String.valueOf((char) (97+i)).toUpperCase();
                List<ProjectVO> projectVOS1 = projectVOS.stream().filter(p -> initial.equals(PinyinUtil.converterToFirstSpell(p.getName()))).collect(Collectors.toList());
                listMap.put(initial,projectVOS1);
                projectVOS.removeAll(projectVOS1);
            }
            listMap.put("#",projectVOS);
            return ResultJson.success(listMap);
        }
        return ResultJson.success(projectList);
    }

    @Deprecated
    @RequestMapping(value = "/project/auto-code")
    public ResultJson getCode() {
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        return ResultJson.success(code);
    }

    @RequestMapping(value = "/project/detail", method = RequestMethod.GET)
    public ResultJson detail(Integer id, Account account,Integer typeId) {
        if (null == id) {
            return ResultJson.fail("参数错误");
        }
        List<Integer> entIds = accountService.getEnterpriseIds(account.getId());
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.withId(id);
        projectQuery.withEnterpriseIds(entIds);
        Project one = projectService.getOne(projectQuery, null);
        if (null == one) {
            return ResultJson.success();
        }
        return ResultJson.success(fillInfo(one,typeId));
    }

    /**
     * 填充返回信息
     * @param one
     * @return
     */
    private ProjectVO fillInfo(Project one,Integer typeId){
        ProjectVO result = new ProjectVO();
        List<Permission> permissions = permissionService.getListByProjectId(null, one.getId());
        BeanUtils.copyProperties(one, result);

        List<Integer> regionIds = new ArrayList<>();
        if (one.getProvinceId() != null) {
            regionIds.add(one.getProvinceId());
        }
        if (one.getCityId() != null) {
            regionIds.add(one.getCityId());
        }
        if (one.getDistrictId() != null) {
            regionIds.add(one.getDistrictId());
        }
        if (0 < regionIds.size()) {
            List<Region> regions = regionService.findByIds(regionIds);
            if (0 < regions.size()) {
                Map<Integer, String> reMap = regions.stream().collect(Collectors.toMap(Region::getId, Region::getName));
                StringBuilder sbd = new StringBuilder();
                if (StringUtils.isNotEmpty(reMap.get(one.getProvinceId()))) {
                    sbd.append(reMap.get(one.getProvinceId()));
                }
                if (StringUtils.isNotEmpty(reMap.get(one.getCityId()))) {
                    sbd.append(reMap.get(one.getCityId()));
                }
                if (StringUtils.isNotEmpty(reMap.get(one.getDistrictId()))) {
                    sbd.append(reMap.get(one.getDistrictId()));
                }
                result.setRegion(sbd.toString());
            }
        }
        Enterprise en = enterpriseService.findById(one.getEnterpriseId());
        if (null == en) {
            throw new DataException("企业不存在");
        }
        result.setEnterpriseName(en.getName());
        result.setPermissions(permissions.stream().map(p -> p.getId()).collect(Collectors.toList()));

        Organization current = organizationService.getById(one.getOrganizationId());
        result.setParentOrgId(current.getParentId());
        if (null != one.getBelongToOrg()){
            Organization belongTo = organizationService.getById(one.getBelongToOrg());
            result.setBelongToOrgName(belongTo.getName());
        }
        //填充扩展信息
        JSONObject extraInfo = JSON.parseObject(projectExtraService.getExtraInfo(one.getId()));
        result.setExtraInfo(extraInfo);
        //设置场景
        Scene scene = sceneDao.selectById(one.getSceneId());
        if(scene != null){
            result.setSceneNames(scene.getName());
        }
        //处理数据
        dealJson (result,typeId);
        return result;
    }

    /**
     * 运管平台查询详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/project/admin/detail", method = RequestMethod.GET)
    public ResultJson adminDetail(Integer id){
        if (null == id) {
            return ResultJson.fail("参数错误");
        }
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.withId(id);
        Project one = projectService.getOne(projectQuery, null);
        if (null == one) {
            return ResultJson.success();
        }
        return ResultJson.success(fillInfo(one,null));
    }

    @RequestMapping(value = "/project/find-ent", method = RequestMethod.GET)
    public ResultJson findEnt(Integer id, Account account) {
        if (null == id) {
            return ResultJson.fail("参数错误");
        }
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.withId(id);
        Project pro = projectService.getOne(projectQuery, account);
        if (null == pro) {
            return ResultJson.success("项目不存在");
        }
        Enterprise ent = enterpriseService.findById(pro.getEnterpriseId());
        if (null == ent) {
            log.error("该项目 {} 所在企业不存在", pro.getName());
            return ResultJson.fail("数据异常");
        }
        return ResultJson.success(ent);
    }

    /**
     * 通过企业id查项目
     *
     * 运营商查它下面项目,入驻企业查它授权项目
     */
    @RequestMapping(value = "/project/findByEntId", method = RequestMethod.POST)
    public ResultJson findByEntId(Integer enterpriseId,@RequestParam(required = false) String keywords) {
        if (null == enterpriseId) {
            return ResultJson.fail("参数错误");
        }
        List<Project> result = projectService.findByEntId(enterpriseId,keywords);
        return ResultJson.success(result);
    }


    /**
     * 业态平台新增项目
     * @param projectDTO
     * @param industryId
     * @param account
     * @return
     */
    @RequestMapping(value = "/project/insert", method = RequestMethod.POST)
    public ResultJson create(@RequestBody ProjectDTO projectDTO, @RequestHeader Short industryId, Account account) {
        projectDTO.setIndustryId(industryId);
        if (null != projectDTO.getEnterpriseId()) {
            Enterprise enterprise = enterpriseService.findById(projectDTO.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("企业不存在");
            }
            projectDTO.setIndustryId(enterprise.getIndustryId());
        }
        if (null != projectDTO.getId()) {
            return projectService.update(projectDTO, account);
        } else {
            return projectService.create(projectDTO, account);
        }
    }

    /**
     * 业态平台新增项目
     * @param projectDTO
     * @param industryId
     * @return
     */
    @RequestMapping(value = "/project/admin/insert", method = RequestMethod.POST)
    public ResultJson insertAdmin(@RequestBody ProjectDTO projectDTO, @RequestHeader Short industryId) {
        projectDTO.setIndustryId(industryId);
        if (null != projectDTO.getEnterpriseId()) {
            Enterprise enterprise = enterpriseService.findById(projectDTO.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("企业不存在");
            }
            projectDTO.setIndustryId(enterprise.getIndustryId());
        }
        if (null != projectDTO.getId()) {
            return projectService.update(projectDTO, null);
        } else {
            return projectService.create(projectDTO, null);
        }
    }

    /**
     * 编辑项目信息（业态平台编辑）
     *
     * @param projectDTO
     * @return
     */
    @PostMapping("/project/edit")
    public ResultJson edit(@RequestBody ProjectDTO projectDTO, Account account) {
        if (null == projectDTO.getParentOrgId()) {
            return ResultJson.fail("缺少所属组织");
        }
        if (null == projectDTO.getId()) {
            return ResultJson.fail("id错误");
        }
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.setId(projectDTO.getId());
        Project project = projectService.getOne(projectQuery, account);
        if (null == project.getId()) {
            return ResultJson.fail("项目不存在");
        }
        Organization organization = organizationService.getById(projectDTO.getParentOrgId());
        if (null == organization) {
            return ResultJson.fail("上级组织错误");
        }
        if (!organization.getEnterpriseId().equals(project.getEnterpriseId())) {
            return ResultJson.fail("数据错误");
        }
        if (StringUtils.isNotEmpty(projectDTO.getHotLine())) {
            if (!ValidatorUtil.isMobile(projectDTO.getHotLine()) && !ValidatorUtil.isTel(projectDTO.getHotLine())) {
                return ResultJson.fail("客服热线格式错误");
            }
        }
        UpdateWrapper<Project> projectUpdateWrapper = new UpdateWrapper<>();
        projectUpdateWrapper.set("building_area", projectDTO.getBuildingArea());
        projectUpdateWrapper.set("occupied_area", projectDTO.getOccupiedArea());
        projectUpdateWrapper.set("land_area", projectDTO.getLandArea());
        projectUpdateWrapper.set("hot_line", projectDTO.getHotLine());
        projectUpdateWrapper.set("plot_ratio", projectDTO.getPlotRatio());
        projectUpdateWrapper.set("green_area", projectDTO.getGreenArea());
        projectUpdateWrapper.set("green_rate", projectDTO.getGreenRate());
        projectUpdateWrapper.set("remark", projectDTO.getRemark());
        projectUpdateWrapper.set("province_id", projectDTO.getProvinceId());
        projectUpdateWrapper.set("city_id", projectDTO.getCityId());
        projectUpdateWrapper.set("district_id", projectDTO.getDistrictId());
        projectUpdateWrapper.set("address", projectDTO.getAddress());
        projectUpdateWrapper.set("longitude", projectDTO.getLongitude());
        projectUpdateWrapper.set("latitude", projectDTO.getLatitude());
        projectUpdateWrapper.set("building_count",projectDTO.getBuildingCount());
        projectUpdateWrapper.set("belong_to_org",projectDTO.getBelongToOrg());
        projectUpdateWrapper.set("complete_date", projectDTO.getCompleteDate());
        projectUpdateWrapper.set("picture_url",projectDTO.getPictureUrl());
        projectUpdateWrapper.set("rich_text",projectDTO.getRichText());
        projectUpdateWrapper.eq("id", project.getId());
        projectService.update(projectUpdateWrapper);
        //记录拓展信息
        projectExtraService.save(JSONObject.toJSONString(projectDTO.getExtraInfo()), project.getId());
        projectLogRecord(account, LogOperationTypeEnum.UPDATE, "编辑项目" + "【" + project.getName() + "】", project);
        return ResultJson.success();
    }

    @RequestMapping(value = "/project/name-check")
    public ResultJson namecheck(@RequestBody ProjectNameCheckedVO checked, Account account) {
        return projectService.nameCheck(checked.getId(), checked.getName(), checked.getEnterpriseId());
    }

    @RequestMapping(value = "/project/delete")
    public ResultJson delete(Integer id, Account account, HttpServletRequest request) {
        ThreadLocalUtil.setIp(IpUtil.getIpAddr(request));
        projectService.delete(id, account);
        return ResultJson.success("操作成功");
    }

    @RequestMapping(value = "/project/ban")
    public ResultJson ban(Account account, Integer id, Boolean isBan, HttpServletRequest request) {
        return projectService.setBan(account, id, isBan);
    }

    /**
     * 表单字段配置（6月版暂定为前端处理）
     *
     * @param industryId
     * @param projectId
     * @param enterpriseId
     * @return
     */
    @RequestMapping(value = "/project/form-config")
    public ResultJson formConfig(@RequestHeader Short industryId,
                                 @RequestParam(value = "projectId", required = false) Integer projectId,
                                 @RequestParam(value = "enterpriseId", required = false) Integer enterpriseId) {


        return ResultJson.success();
    }

    /**
     * 按城市划分项目，查询所有业态
     *
     * @param projectQuery
     * @return
     */
    @RequestMapping(value = "/project/group-by-city", method = RequestMethod.POST)
    public ResultJson groupByCity(@RequestBody ProjectQuery projectQuery) {
        List<Project> projectList = projectService.list(projectQuery, null);
        if (CollectionUtils.isNotEmpty(projectList)) {
            List<Integer> cityIdList = projectList.stream().map(Project::getCityId).collect(Collectors.toList());
            List<Region> regions = regionService.findByIds(cityIdList);
            Map<Integer, List<Project>> projectMap = projectList.stream().filter(e -> null != e.getCityId()).collect(Collectors.groupingBy(Project::getCityId));
            List<ProjectByCityVO> projectByCityVOS = regions.stream().map(region -> {
                ProjectByCityVO cityVO = new ProjectByCityVO();
                cityVO.setCityId(region.getId());
                cityVO.setCityName(region.getName());
                cityVO.setProjectList(projectMap.get(region.getId()));
                return cityVO;
            }).collect(Collectors.toList());
            return ResultJson.successWithResult(projectByCityVOS);
        }

        return ResultJson.fail("项目信息不存在");
    }

    /**
     * 根据经纬度查询距离最近项目
     *
     * @param projectQuery
     * @return
     */
    @RequestMapping(value = "/project/closest", method = RequestMethod.POST)
    public ResultJson queryClosest(@RequestBody ProjectQuery projectQuery) {
        if (MyStringUtils.isEmpty(projectQuery.getLatitude()) || MyStringUtils.isEmpty(projectQuery.getLongitude())) {
            return ResultJson.fail("参数错误");
        }

        List<Project> projectList = projectService.list(projectQuery, null);
        if (CollectionUtils.isEmpty(projectList)) {
            return ResultJson.fail("项目数据不存在");
        }
        Project result = projectList.get(0);

        projectList = projectList.stream().filter(project ->
                MyStringUtils.isNotEmpty(project.getLatitude()) && MyStringUtils.isNotEmpty(project.getLongitude())
        ).collect(Collectors.toList());
        double distance = -1;
        for (Project project : projectList) {
            double tmpDistance = MyStringUtils.getDistance(Double.parseDouble(projectQuery.getLatitude()),
                    Double.parseDouble(projectQuery.getLongitude()),
                    Double.parseDouble(project.getLatitude()),
                    Double.parseDouble(project.getLongitude()));
            if (distance == -1) {
                distance = tmpDistance;
                result = project;
            }
            if (tmpDistance < distance) {
                distance = tmpDistance;
                result = project;
            }
        }

        return ResultJson.successWithResult(result);
    }

    private List<ProjectVO> convertView(List<Project> projects,Integer typeId) {
        if (projects.isEmpty()) {
            return Collections.emptyList();
        }
        // 有效期剩余时间计算 项目所在省市区获取
        List<Integer> regionSet = new ArrayList<>();
        List<ProjectVO> result = new ArrayList<>(projects.size());
        Map<Integer, String> regionNameMap = new HashMap<>();
        if (!projects.isEmpty()) {
            projects.stream().forEach(p -> {
                if (null != p.getProvinceId()) {
                    regionSet.add(p.getProvinceId());
                }
                if (null != p.getCityId()) {
                    regionSet.add(p.getCityId());
                }
                if (null != p.getDistrictId()) {
                    regionSet.add(p.getDistrictId());
                }
            });
            List<Region> regions = regionService.findByIds(regionSet);
            regionNameMap = regions.stream().collect(Collectors.toMap(Region::getId, Region::getName));
        }
        List<Integer> collect = projects.stream().map(p -> p.getOrganizationId()).collect(Collectors.toList());
        // 所属组织
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.setIds(collect);
        organizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.id.intValue(), OrganizationTypeEnum.ORG.id.intValue()));
        Map<Integer, String> map = organizationService.batchFullName(organizationQuery);

        // 回填parentOrgId
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.select("id", "parent_id");
        organizationQueryWrapper.in("id", collect);
        List<Organization> list = organizationService.list(organizationQueryWrapper);
        Map<Integer, Integer> parentOrgMap = list.stream().collect(Collectors.toMap(Organization::getId, Organization::getParentId));

        List<Enterprise> enterprises = enterpriseService.listByIds(projects.stream().map(i -> i.getEnterpriseId()).distinct().collect(Collectors.toList()));
        Map<Integer, String> entMap = enterprises.stream().collect(Collectors.toMap(Enterprise::getId, Enterprise::getName));
        //所在组织
        List<Integer> orgIds = projects.stream().map(Project::getBelongToOrg).collect(Collectors.toList());
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",orgIds);
        List<Organization> organizationList = organizationService.list(queryWrapper);
        Map<Integer, String> orgMap = organizationList.stream().collect(Collectors.toMap(Organization::getId,Organization::getName));
        for (Project p : projects) {
            //处理数据
            dealJson(p,typeId);
            ProjectVO projectViewDTO = new ProjectVO();
            BeanUtils.copyProperties(p, projectViewDTO);
            Long remainder = DateUtils.periodDays(LocalDate.now(), DateUtils.toLocalDate(p.getValidityDateEnd()));
            // 剩余时间
            projectViewDTO.setRemainder(remainder.intValue());
            StringBuilder sbd = new StringBuilder();

            if (null != p.getProvinceId()) {
                sbd.append(regionNameMap.get(p.getProvinceId()));
            }
            if (null != p.getCityId()) {
                sbd.append(regionNameMap.get(p.getCityId()));
            }
            if (null != p.getDistrictId()) {
                sbd.append(regionNameMap.get(p.getDistrictId()));
            }
            if (StringUtils.isNotEmpty(sbd.toString())) {
                projectViewDTO.setRegion(sbd.toString());
            }
            if (null != map) {
                projectViewDTO.setOrganizations(map.get(p.getOrganizationId()));
            }
            if (null != p.getBelongToOrg()){
                projectViewDTO.setBelongToOrgName(orgMap.get(p.getBelongToOrg()));
            }
            projectViewDTO.setEnterpriseName(entMap.get(p.getEnterpriseId()));
            projectViewDTO.setParentOrgId(parentOrgMap.get(p.getOrganizationId()));
            //设置场景
            Scene scene = sceneDao.selectById(p.getSceneId());
            if(scene != null){
                projectViewDTO.setSceneNames(scene.getName());
            }
            result.add(projectViewDTO);
        }

        return result;
    }

    @Data
    static class Query {

        private Page page;

        private ProjectQuery projectQuery;

    }

    public void projectLogRecord(Account operateAccount, LogOperationTypeEnum logOperationTypeEnum, String operateContent, Project project) {
        OperateLog operateLog = new OperateLog();
        operateLog.setMenu(ModuleTypeEnum.PROJECT_MANAGE.getName());
        operateLog.setOperateType(logOperationTypeEnum.getType());
        operateLog.setOperateContent(operateContent);
        operateLog.setEnterpriseId(project.getEnterpriseId());
        operateLog.setProjectId(project.getId());
        operateLog.setProjectName(project.getName());
        operateLog.setIp(ThreadLocalUtil.getIp());
        operateLog.setIndustryId(ThreadLocalUtil.getIndustryId());
        if (null == operateAccount) {
            operateAccount = ThreadLocalUtil.getAccount();
        }
        if (null != operateAccount) {
            operateLog.setIndustryId(operateAccount.getIndustryId());
            operateLog.setAccountId(operateAccount.getId());
            operateLog.setLoginName(operateAccount.getLoginName());
            operateLog.setName(operateAccount.getName());
            //填充企业ids+项目ids
            List<Enterprise> enterprises = enterpriseService.list(null,operateAccount);
            if (!org.springframework.util.CollectionUtils.isEmpty(enterprises)){
                operateLog.setEnterpriseIds(enterprises.stream().map(Enterprise::getId).collect(Collectors.toList()));
            }
            List<AccountDetailDTO> projectInfoList = accountService.getAccountProjectInfoByIdList(Collections.singletonList(operateAccount.getId()));
            operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            if (!org.springframework.util.CollectionUtils.isEmpty(projectInfoList)){
                operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            }
        }
        logTemplate.addOperateLog(operateLog);

    }

    @RequestMapping(value = "/project/get-field-sort")
    public ResultJson getFieldSort(Account account) {
        Set<String> range = redisTemplate.opsForZSet().range(PROJECT_PAGE_FIELD + "_" + account.getId(), 0, -1);
        return ResultJson.success(range);
    }

    /**
     * 设置列表展示的字段
     *
     * @param arr
     * @param account
     * @return
     */
    @RequestMapping(value = "/project/set-field-sort")
    public ResultJson setFieldSort(@RequestBody List<String> arr, Account account) {
        if (CollectionUtils.isEmpty(arr)) {
            return ResultJson.fail("空数据");
        }
        Set<DefaultTypedTuple<String>> set = new HashSet<>();
        for (int i = 0; i < arr.size(); i++) {
            DefaultTypedTuple<String> tuple1 = new DefaultTypedTuple<String>(arr.get(i), (double) i);
            set.add(tuple1);
        }
        redisTemplate.opsForZSet().removeRange(PROJECT_PAGE_FIELD + "_" + account.getId(), 0, 100);
        redisTemplate.opsForZSet().add(PROJECT_PAGE_FIELD + "_" + account.getId(), set);
        return ResultJson.success();
    }

    /**
     * 兼容历史数据
     */
    private void dealJson (Project param,Integer typeId){
        if(typeId == null){
            return;
        }
        QueryWrapper<OrganizationType> organizationTypeQueryWrapper = new QueryWrapper<>();
        organizationTypeQueryWrapper.eq("id", typeId);
        OrganizationType organizationType = organizationTypeService.getOne(organizationTypeQueryWrapper);
        String source = organizationType.getSource();
        if(StringUtils.isEmpty(source)){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        JSONObject sourceJson = JSON.parseObject(source);
        JSONArray fields = sourceJson.getJSONArray("fields");
        if(CollectionUtil.isNotEmpty(fields)) {
            for (int i = 0; i < fields.size(); i++) {
                JSONObject fieldJsonObject = fields.getJSONObject(i);
                fieldJsonObject.remove("__config__");
                String vModel = fieldJsonObject.getString("vModel");
                //兼容以前数据
                if ("name".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getName() != null ? param.getName() : "");
                    map.put("name",param.getName() != null ? param.getName() : "");
                } else if ("code".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getCode() != null ? param.getCode() : "");
                    map.put("code",param.getCode() != null ? param.getCode() : "");
                } else {
                    if(param.getExpand() != null) {
                        JSONObject jsonObject = JSON.parseObject(param.getExpand());
                        if(jsonObject.get(vModel) != null) {
                            fields.getJSONObject(i).put("defaultValue", jsonObject.get(vModel));
                            map.put(vModel,jsonObject.get(vModel));
                        }else{
                            map.put(vModel,"");
                        }
                    }else{
                        map.put(vModel,"");
                    }
                }
            }
        }
        param.setExpand(JSON.toJSONString(sourceJson));
        param.setFullData(JSON.toJSONString(map));
    }

}


